<template>
  <div class="app-container">
    <div class="search-container">
      <el-form inline label-width="68px" ref="queryFromRef" :model="queryParams">
        <el-form-item label="表名称">
          <el-input v-model="queryParams.tableName" placeholder="" />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery" class="filter-item">
            <i-ep-refresh />重置
          </el-button>
          <el-button v-hasPerm="['sys:tableConfig:init']" type="success" @click="handleInitData()">
            <template #icon><i-ep-plus /></template>
            初始化数据
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table v-loading="loading" stripe :data="list" style="width: 100%">
        <el-table-column label="ID" width="50" prop="id" min-width="50" />
        <el-table-column label="表名称" width="200" prop="tableName" min-width="100" />
        <el-table-column label="业务名称" width="200" prop="businessName" min-width="200" />
        <el-table-column label="模块名称" width="200" prop="moduleName" min-width="200" />
        <el-table-column label="实体名称" width="200" prop="entityName" min-width="200" />
        <el-table-column label="包名称" width="200" prop="packageName" min-width="300" />

        <el-table-column fixed="right" label="操作" width="350">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:tableConfig:update']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              表配置
            </el-button>
            <el-button
              v-hasPerm="['sys:tableConfig:update']"
              type="danger"
              link
              size="small"
              @click.stop="handleResetColumn(scope.row.id)"
            >
              <i-ep-delete />
              清除字段配置
            </el-button>
            <el-button
              v-hasPerm="['sys:tableConfig:update']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog2(scope.row.id)"
            >
              <i-ep-edit />
              字段配置
            </el-button>

            <el-button
              v-hasPerm="['sys:tableConfig:viewCode']"
              type="primary"
              link
              size="small"
              @click.stop="handleOpenDialog3(scope.row.id)"
            >
              <i-ep-view />
              查看代码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog" size="90%">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="表名称" prop="tableName">
          <el-input v-model="formData.tableName" placeholder="" />
        </el-form-item>
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="formData.businessName" placeholder="" />
        </el-form-item>
        <el-form-item label="包名称" prop="packageName">
          <el-input v-model="formData.packageName" placeholder="" />
        </el-form-item>
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="formData.moduleName" placeholder="" />
        </el-form-item>
        <el-form-item label="实体名称" prop="entityName">
          <el-input v-model="formData.entityName" placeholder="" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="" />
        </el-form-item>
        <el-form-item label="urlPrefix" prop="author">
          <el-input v-model="formData.urlPrefix" placeholder="" />
        </el-form-item>
        <el-form-item label="权限字符串前缀" prop="author">
          <el-input v-model="formData.roleName" placeholder="" />
        </el-form-item>
        <el-form-item label="API标签前缀" prop="author">
          <el-input v-model="formData.tagPrefix" placeholder="" />
        </el-form-item>
        <!-- <el-form-item label="上级菜单ID" prop="author">
          <el-input v-model="formData.menuParentId" placeholder="" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer
      v-model="dialog2.visible"
      :title="dialog2.title"
      @close="handleCloseDialog"
      size="90%"
    >
      <el-table
        v-loading="loading"
        row-key="id"
        :element-loading-text="loadingText"
        highlight--currentrow
        :data="formData2"
      >
        <el-table-column label="列名" width="150">
          <template #default="scope">
            {{ scope.row.columnName }}
          </template>
        </el-table-column>
        <el-table-column label="列类型" width="150">
          <template #default="scope">
            {{ scope.row.columnType }}
          </template>
        </el-table-column>
        <el-table-column label="字段名" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.fieldName" />
          </template>
        </el-table-column>
        <el-table-column label="字段类型" width="100">
          <template #default="scope">
            {{ scope.row.fieldType }}
          </template>
        </el-table-column>
        <el-table-column label="字段注释" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.fieldComment" />
          </template>
        </el-table-column>

        <el-table-column label="长度" width="60">
          <template #default="scope">
            <el-input v-model="scope.row.maxLength" />
          </template>
        </el-table-column>

        <el-table-column width="70">
          <template #header>
            <div class="flex-y-center">
              <span>列表</span>
              <el-checkbox
                class="ml-1"
                v-model="isCheckAllList"
                @change="toggleCheckAll('isShowInList', isCheckAllList)"
              />
            </div>
          </template>

          <template #default="scope">
            <el-checkbox v-model="scope.row.isShowInList" :true-value="1" :false-value="0" />
          </template>
        </el-table-column>

        <el-table-column width="70">
          <template #header>
            <div class="flex-y-center">
              <span>查询</span>
              <el-checkbox
                class="ml-1"
                v-model="isCheckAllQuery"
                @change="toggleCheckAll('isShowInQuery', isCheckAllQuery)"
              />
            </div>
          </template>
          <template #default="scope">
            <el-checkbox v-model="scope.row.isShowInQuery" :true-value="1" :false-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="查询方式" min-width="120">
          <template #default="scope">
            <el-select
              v-model="scope.row.queryType"
              placeholder="请选择"
              v-if="scope.row.isShowInQuery || scope.row.isShowInQuery === 1"
            >
              <el-option
                v-for="(item, key) in queryTypeOptions"
                :key="key"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column width="70">
          <template #header>
            <div class="flex-y-center">
              <span>表单</span>
              <el-checkbox
                class="ml-1"
                v-model="isCheckAllForm"
                @change="toggleCheckAll('isShowInForm', isCheckAllForm)"
              />
            </div>
          </template>

          <template #default="scope">
            <el-checkbox v-model="scope.row.isShowInForm" :true-value="1" :false-value="0" />
          </template>
        </el-table-column>

        <el-table-column label="必填" width="70">
          <template #default="scope">
            <el-checkbox
              v-model="scope.row.isRequired"
              :true-value="1"
              :false-value="0"
              v-if="scope.row.isShowInForm || scope.row.isShowInQuery === 1"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column label="表单类型" min-width="120">
          <template #default="scope">
            <el-select
              v-model="scope.row.formType"
              placeholder="请选择"
              v-if="
                scope.row.isShowInQuery ||
                scope.row.isShowInQuery === 1 ||
                scope.row.isShowInForm ||
                scope.row.isShowInForm === 1
              "
            >
              <el-option
                v-for="(item, key) in formTypeOptions"
                :key="key"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column label="字典类型" min-width="100">
          <template #default="scope">
            <el-select
              v-if="scope.row.formType === 2"
              v-model="scope.row.dictType"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in dictOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm2">确 定</el-button>
          <el-button @click="handleCloseDialog2">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer
      v-model="dialogCodeVisable"
      title="查看代码"
      @close="handleCloseDialogCode"
      size="90%"
    >
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button v-hasPerm="['sys:codeGen:generator']" type="danger" @click="handleCodeQuery()">
            <template #icon><i-ep-refresh /></template>
            重新加载代码
          </el-button>
        </template>

        <el-tabs v-model="activeName" @tab-click="handleCodeClick">
          <el-tab-pane label="Entity.java" name="Entity">
            <Codemirror
              v-model:value="codeGenDto.entityCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefEntity"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="Repository.java" name="Repository">
            <Codemirror
              v-model:value="codeGenDto.repositoryCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefRepository"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="Service.java" name="Service">
            <Codemirror
              v-model:value="codeGenDto.serviceCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefService"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="ServiceImpl.java" name="ServiceImpl">
            <Codemirror
              v-model:value="codeGenDto.serviceImplCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefServiceImpl"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="DTO.java" name="DTO">
            <Codemirror
              v-model:value="codeGenDto.dtoCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefDTO"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="QueryDTO.java" name="QueryDTO">
            <Codemirror
              v-model:value="codeGenDto.dtoQueryCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefQueryDTO"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="FormDTO.java" name="FormDTO">
            <Codemirror
              v-model:value="codeGenDto.dtoFormCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefFormDTO"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="Controller.java" name="Controller">
            <Codemirror
              v-model:value="codeGenDto.controllerCode"
              :border="true"
              options="{{ mode:'text/x-java' }}"
              ref="cmRefController"
              height="1000"
              width="100%"
            />
          </el-tab-pane>
          <el-tab-pane label="index.vue" name="VUE"
            ><Codemirror
              v-model:value="codeGenDto.vueCode"
              :border="true"
              options="{{   mode: 'text/javascript' }}"
              ref="cmRefVue"
              height="1000"
              width="100%"
          /></el-tab-pane>
        </el-tabs>
      </el-card>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'TableConfig',
  inheritAttrs: false
})

import 'codemirror/mode/javascript/javascript.js'
import Codemirror from 'codemirror-editor-vue3'

import { ElForm, ElTable } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request.ts'

const BASE_URL = '/api/yyplatform/admin/generator/tableConfig/'
const BASE_URL2 = '/api/yyplatform/admin/generator/columnConfig/'

const list = ref([])
const total = ref(0)
const loading = ref(false)

const addFormRef = ref(ElForm)
const formData = ref({
  id: '',
  tableName: '',
  moduleName: '',
  packageName: '',
  businessName: '',
  entityName: '',
  author: 'sleepforests',
  menuParentId: 0,
  urlPrefix: '',
  tagPrefix: '',
  roleName: ''
})
const queryFromRef = ref()
const dialog = ref({
  title: '',
  visible: false
})

const queryParams = ref({
  tableName: '',
  pageNum: 1,
  pageSize: 20
})

function handleCloseDialog() {
  dialog.value = {
    title: '',
    visible: false
  }
  formData.value = {
    id: '',
    tableName: '',
    moduleName: '',
    packageName: '',
    businessName: '',
    entityName: '',
    author: '',
    menuParentId: 0
  }
}

async function handleInitData() {
  request({
    url: `${BASE_URL}/init`,
    method: 'get'
  }).then(async () => {
    ElMessage.success('初始化成功')
    await handleQuery()
  })
}

function handleResetColumn(id) {
  request({
    url: `${BASE_URL}/reset?id=${id}`,
    method: 'post'
  }).then(async () => {
    ElMessage.success('重置成功')
    await handleQuery()
  })
}

function handleOpenDialog(id) {
  if (id) {
    dialog.value.visible = true
    dialog.value.title = '表配置'
    request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    }).then((res) => {
      console.log(res, 'res')
      formData.value = res
    })
  }
}
async function submitForm() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}
function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

async function handleResetQuery() {
  await handleQuery()
}

async function handleQuery() {
  console.log(queryParams.value, 'queryParams')

  loading.value = true

  let queryRes = await request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: {
      ...queryParams.value
    }
  })

  loading.value = false
  list.value = queryRes.content
  total.value = parseInt(queryRes.totalElements)
}
// ======================================================================
const queryTypeOptions = ref([
  { value: 1, label: '=' },
  { value: 2, label: 'LIKE "%s%" ' },
  { value: 3, label: 'IN' },
  { value: 4, label: 'BETWEEN' },
  { value: 5, label: '>' },
  { value: 6, label: '<' },
  { value: 7, label: '>=' },
  { value: 8, label: '<=' },
  { value: 9, label: 'LIKE "%s" ' },
  { value: 10, label: 'LIKE "s%" ' }
])

const formTypeOptions = ref([
  { value: 1, label: '输入框' },
  { value: 2, label: '下拉框' },
  { value: 3, label: '单选框' },
  { value: 4, label: '复选框' },
  { value: 5, label: '数字输入框' },
  { value: 6, label: '开关' },
  { value: 7, label: '文本域' },
  { value: 8, label: '日期框' },
  { value: 9, label: '日期时间框' }
])

// todo
const dictOptions = ref([])

const dialog2 = ref({
  title: '',
  visible: false
})

const addFormRef2 = ref(ElForm)
const formData2 = ref([])

function handleCloseDialog2() {
  dialog2.value = {
    visible: false
  }
}
function handleOpenDialog2(id) {
  request({
    url: `${BASE_URL2}/query?tableConfigId=${id}`,
    method: 'get'
  }).then((res) => {
    console.log(res, 'res')
    formData2.value = res
    dialog2.value.visible = true
    dialog2.value.title = '字段配置'
  })
}

async function submitForm2() {
  console.log(formData2.value, 'formData2')

  let updateRes = await request({
    url: `${BASE_URL2}/saveBatch`,
    method: 'post',
    data: formData2.value
  })
  ElMessage.success('修改成功')
  handleCloseDialog2()
}

function toggleCheckAll(key, value) {
  const fieldConfigs = formData2.value

  if (fieldConfigs) {
    fieldConfigs.forEach((row) => {
      row[key] = value ? 1 : 0
    })
  }
}

// ========================================================================
// import router from '@/router'
import 'codemirror/theme/dracula.css'

const dialogCodeVisable = ref(false)
const codeGenDto = ref({})
const codeId = ref(0)
const activeName = ref('Entity')

const cmRefEntity = ref(null)
const cmRefRepository = ref(null)
const cmRefService = ref(null)
const cmRefServiceImpl = ref(null)
const cmRefDTO = ref(null)
const cmRefFormDTO = ref(null)
const cmRefQueryDTO = ref(null)
const cmRefVue = ref(null)
const cmRefController = ref(null)

async function handleOpenDialog3(id) {
  //const path = '/generator/codeGen'
  //router.push({ path: path, query: { id: id } })
  dialogCodeVisable.value = true
  codeId.value = id
  await handleCodeQuery(id)
}

function handleCloseDialogCode() {
  dialogCodeVisable.value = false
  codeId.value = 0
}

const onCodeChange = (val, cm) => {
  console.log(val)
  console.log(cm.getValue())
}

const handleCodeClick = (tab, event) => {
  console.log(tab, event)
  setTimeout(() => {
    cmRefEntity.value.refresh()
    cmRefRepository.value.refresh()
    cmRefService.value.refresh()
    cmRefServiceImpl.value.refresh()
    cmRefDTO.value.refresh()
    cmRefFormDTO.value.refresh()
    cmRefQueryDTO.value.refresh()
    cmRefVue.value.refresh()
    cmRefController.value.refresh()
    console.log('refresh')
  }, 1)
}

async function handleCodeQuery() {
  //let id = route.query.id
  let id = codeId.value
  let res = await request({
    url: '/api/yyplatform/admin/generator/codeGen/generator?id=' + id,
    method: 'get'
  })
  codeGenDto.value = res
  setTimeout(() => {
    cmRefEntity.value.refresh()
    cmRefRepository.value.refresh()
    cmRefService.value.refresh()
    cmRefServiceImpl.value.refresh()
    cmRefDTO.value.refresh()
    cmRefFormDTO.value.refresh()
    cmRefQueryDTO.value.refresh()
    cmRefVue.value.refresh()
    cmRefController.value.refresh()
  }, 1)
}

// ========================================================================

onMounted(async () => {
  await handleQuery()
})
</script>
